//
//  PublicView.m
//  YiChat20160706
//
//  Created by 李政 on 16/7/11.
//  Copyright © 2016年 ZhiYou. All rights reserved.
//

#import "PublicView.h"

#import "CollectionViewCell.h"

#import <SDWebImage/UIButton+WebCache.h>

#import "NetTool.h"

#import "Util.h"

#import <ASIHTTPRequest/ASIHTTPRequest.h>

#import "DownloadManager.h"


#define ITEM_WIDTH      (SCREEN_WIDTH - 50) * 1.0 /3

#define ITEM_SPACING    10

@implementation PublicView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc] init];
        
        
        fl.sectionInset = UIEdgeInsetsMake(10, 10, 20, 10);
        
        //
        
        _taskDictionary = [[NSMutableDictionary alloc] init];
        
        
        
        fl.itemSize = CGSizeMake(ITEM_WIDTH, ITEM_WIDTH + 50);
        
        fl.minimumInteritemSpacing = ITEM_SPACING;
        
        collection = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:fl];
        
        collection.backgroundColor = [UIColor clearColor];
        
        collection.delegate = self;
        collection.dataSource = self;
        
        
        [collection registerNib:[UINib nibWithNibName:@"CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
        
        [self addSubview:collection];
    }
    return self;
}


- (void)reloadCollectionData
{
    
    [collection reloadData];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    
    
    
    return _dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = _dataArray[indexPath.row];
    
    
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    [cell.percentBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:dic[@"image_url"]] forState:UIControlStateNormal];
    
    if ([Util checkTheFileDidDownloadWithFile:dic])
    {
        //100表示下载完毕
        cell.percentBtn.downloadState = UIButtonTypeDidDownload;
        
        cell.top.constant = ITEM_WIDTH;
        
        cell.height.constant = 0;
        
        [cell.percentBtn setTitle:@"查看" forState:UIControlStateNormal];
    }
    else
    {
        float percent = [Util getFileSizeWithFile:dic] * 1.0/[dic[@"length"] longLongValue];
        
        cell.top.constant = ITEM_WIDTH * percent;
        
        cell.height.constant = ITEM_WIDTH * (1 - percent) ;
        
        cell.percentBtn.downloadState = UIButtonTypeDownloadPart;
        
      //  NSString *title = [NSString stringWithFormat:@"下载%.2f%%",percent * 100];
        
        [cell.percentBtn setTitle:@"下载" forState:UIControlStateNormal];
    }
    
    [cell.percentBtn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.percentBtn.tag = 1000 + indexPath.row;
    
    cell.nameLabel.text = dic[@"tname"];
    
    
    return cell;
}

- (void)buttonClicked:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
    int tag = (int)button.tag - 1000;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:tag inSection:0];
    
    CollectionViewCell *cell = (CollectionViewCell *)[collection cellForItemAtIndexPath:indexPath];

    
    NSDictionary *dic = _dataArray[tag];
    
    
    
    
    if (cell.percentBtn.downloadState == UIButtonTypeDidDownload)
    {
        //表示文件已经下载完毕了
        
        //直接跳转查看界面
    }
    
    else if(cell.percentBtn.downloadState == UIButtonTypeDownloadPart)
    {
        //表示文件一点也没有下载或者已经下载了一半,执行下载操作
        
        
        [self downloadTheFile:dic collectionCell:cell];
    }
    else  //cell.percentBtn.downloadState == UIButtonTypeDownloading
    {
        //表示文件正在下载状态
        
        [self pauseTheDownloadWithTheFile:dic Cell:cell];
        
    }
}

- (void)pauseTheDownloadWithTheFile:(NSDictionary *)dic Cell:(CollectionViewCell *)cell
{
    NSOperationQueue *queue = [ASIHTTPRequest sharedQueue];
    
    NSArray *operationsArray = queue.operations;
    
    for (ASIHTTPRequest *request in operationsArray) {
        if (request.tag == cell.percentBtn.tag) {
            [request cancel];
        }
    }
    
    cell.percentBtn.downloadState = UIButtonTypeDownloadPart;

}


- (void)downloadTheFile:(NSDictionary *)dic collectionCell:(CollectionViewCell *)cell
{
    

    //使用afnetworking断点下载时无法支持程序重启后断点下载功能，改用ASIHttpRequest
    
    
    
    /*
    cell.percentBtn.downloadState = UIButtonTypeDownloading;
    
    NSString *fileUrl = dic[@"url"];
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    
    mgr.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fileUrl]];
    
    
    long long size = [Util getFileSizeWithFile:dic];
    
    [request addValue:[NSString stringWithFormat:@"bytes=%lld-",size] forHTTPHeaderField:@"Range"];
    
    NSURLSessionDownloadTask *task = [mgr downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            float percent = downloadProgress.completedUnitCount * 1.0/downloadProgress.totalUnitCount;
            
            cell.top.constant = ITEM_WIDTH * percent;
            
            cell.height.constant = ITEM_WIDTH * (1 - percent);
            
            NSString *titleStr = [NSString stringWithFormat:@"%.2f%%",percent * 100];
            
            [cell.percentBtn setTitle:titleStr forState:UIControlStateNormal];
            
            
            if (percent == 1)
            {
                cell.percentBtn.tag = 100;
                
                [cell.percentBtn setTitle:@"查看" forState:UIControlStateNormal];
                
                NSLog(@"下载完成!");

            }
            
        });
        
        
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSLog(@"--------%@",targetPath);
        
        return [NSURL fileURLWithPath:[Util getDestinationFilePathWithFile:dic]];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        NSLog(@"-------%@",filePath);
    }];
    
    [_taskDictionary setObject:task forKey:@(cell.percentBtn.tag)];
    
    [task resume];
    */
    
    cell.percentBtn.downloadState = UIButtonTypeDownloading;
    
    
    NSString *fileUrl = dic[@"url"];
    
    NSString *desPath = [Util getDestinationFilePathWithFile:dic];
    
    NSString *tmpPath = [Util getTempFilePathWithFile:dic];
    
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:fileUrl]];
    
    request.tag = cell.percentBtn.tag;
    
    [request setTemporaryFileDownloadPath:tmpPath];
    
    [request setDownloadDestinationPath:desPath];
    
    request.allowResumeForFileDownloads = YES;
    
    request.downloadProgressDelegate = cell;
    
    
    [request setCompletionBlock:^{
        NSLog(@"下载结束!");
        
//        cell.downloadState = NSButtonStateFinished;
        
        cell.percentBtn.downloadState = UIButtonTypeDidDownload;
        
        [cell.percentBtn setTitle:@"查看" forState:UIControlStateNormal];
        
        [[DownloadManager shared] addObject:dic];
    }];
    
    [request startAsynchronous];
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
